import os
import ast

from flask import Flask, request, jsonify
from flask_cors import CORS

from fit_py_ask_number_demo.components.info_extract import info_extract_impl
from fit_py_ask_number_demo.components.dsl_generate import get_complete_query_impl, dsl_generate_impl
from fit_py_ask_number_demo.components.question_classify import question_classify_impl
from fit_py_ask_number_demo.components.sql_constructor import dsl2sql_impl
from fit_py_ask_number_demo.components.question_route import question_route_impl
from fit_py_ask_number_demo.client import llm_client, sql_client
from fit_py_ask_number_demo.data_managers.prompt_manager import PromptManager
from fit_py_ask_number_demo.data_managers.query_model_manager import QueryModelManager
from fit_py_ask_number_demo.data_managers.enum_manager import EnumManager
from fit_py_ask_number_demo.data_managers.synonym_manager import SynonymManager
from fit_py_ask_number_demo.data_managers.rule_manager import RuleManager


app = Flask(__name__)
CORS(app)


@app.route('/api/prompts', methods=['GET'])
def get_all_prompts():
    try:
        print("正在获取所有prompts...")  # 添加日志
        prompts = PromptManager().list_all_prompts()
        print("获取到的prompts:", prompts)  # 添加日志
        return {"prompts": prompts}
    except Exception as e:
        print("获取prompts时发生错误:", str(e))  # 添加错误日志
        return jsonify({'error': str(e)}), 500


@app.route('/api/prompts', methods=['POST'])
def update_prompt():
    """
    更新单个 prompt 的接口
    """
    # 获取请求数据
    data = request.json
    name = data.get('name')  # 名称
    new_prompt = data.get('new_prompt')  # 新的 prompt 值

    # 检查参数是否有效
    if not name or not new_prompt:
        return jsonify({'success': False, 'message': 'name 和 new_prompt 不能为空'}), 400

    try:
        # 调用更新方法
        result = PromptManager().update_prompt_by_name(name, new_prompt)
        if result:
            return jsonify({'success': True, 'message': '更新成功'})
        else:
            return jsonify({'success': False, 'message': '更新失败'}), 500
    except Exception as e:
        return jsonify({'success': False, 'message': f'更新过程中发生错误: {str(e)}'}), 500


@app.route('/api/dsl-examples', methods=['GET'])
def get_all_dsl_examples():
    try:
        prompts = QueryModelManager().list_all_data("dsl_example")
        return {"dsl examples": prompts}
    except Exception as e:
        print("获取dsl example时发生错误:", str(e))
        return jsonify({'error': str(e)}), 500


@app.route('/api/dsl-examples', methods=['POST'])
def update_dsl_example():
    """
    更新单个 prompt 的接口
    """
    # 获取请求数据
    data = request.json
    query_type = data.get('query_type')
    new_dsl_example = data.get('new_dsl_example')  # 新的 prompt 值

    # 检查参数是否有效
    if not query_type or not new_dsl_example:
        return jsonify({'success': False, 'message': 'query 和 new_prompt 不能为空'}), 400

    try:
        # 调用更新方法
        result = QueryModelManager().update_data_by_query_type("dsl_example", query_type, new_dsl_example)
        if result:
            return jsonify({'success': True, 'message': '更新成功'})
        else:
            return jsonify({'success': False, 'message': '更新失败'}), 500
    except Exception as e:
        return jsonify({'success': False, 'message': f'更新过程中发生错误: {str(e)}'}), 500


@app.route('/api/sql-templates', methods=['GET'])
def get_all_sql_templates():
    try:
        prompts = QueryModelManager().list_all_data("sql_template")
        return {"sql templates": prompts}
    except Exception as e:
        print("获取sql template时发生错误:", str(e))
        return jsonify({'error': str(e)}), 500


@app.route('/api/sql-templates', methods=['POST'])
def update_sql_template():
    """
    更新单个 prompt 的接口
    """
    # 获取请求数据
    data = request.json
    query_type = data.get('query_type')
    new_sql_template = data.get('new_sql_template')

    # 检查参数是否有效
    if not query_type or not new_sql_template:
        return jsonify({'success': False, 'message': 'query_type 和 new_prompt 不能为空'}), 400

    try:
        # 调用更新方法
        result = QueryModelManager().update_data_by_query_type("sql_template", query_type, new_sql_template)
        if result:
            return jsonify({'success': True, 'message': '更新成功'})
        else:
            return jsonify({'success': False, 'message': '更新失败'}), 500
    except Exception as e:
        return jsonify({'success': False, 'message': f'更新过程中发生错误: {str(e)}'}), 500

@app.route('/api/pre-ask-number', methods=['POST'])
def pre_ask_number():
    print(request.json)
    query = request.json.get('query')
    intention = question_route_impl(query)
    print(intention)
    if intention != "data":
        return llm_client.deepseek_client("", query)

    new_query, field_info, semantic_info, ambiguous_info = info_extract_impl(query)
    print(new_query)
    query_type = question_classify_impl(new_query, semantic_info)
    print(query_type, field_info, semantic_info, ambiguous_info)
    resp = {
        "query": new_query,
        "field_info": ast.literal_eval(field_info),
        "semantic_info": semantic_info,
        "ambiguous_info": ambiguous_info,
        "query_type": query_type
    }
    return jsonify(resp), 200


@app.route('/api/post-ask-number', methods=['POST'])
def post_ask_number():
    query = request.json.get('query')
    semantic_info = request.json.get('semantic_info')
    field_info = request.json.get('field_info')
    query_type = request.json.get('query_type')
    complete_query = get_complete_query_impl(query, semantic_info, field_info)
    print(complete_query)
    dsl = dsl_generate_impl(complete_query, query_type)
    print(dsl)
    sql = dsl2sql_impl(dsl, query_type)
    print(sql)
    db_path = os.path.join(os.path.dirname(__file__), '../database/kpi2.db')
    result = sql_client.SqlLiteClient(db_path).execute_sql(sql)
    print(result)
    columns = list(result[0].keys())

    # 初始化数据对象
    data_object = {column: [] for column in columns}

    # 填充数据对象
    for item in result:
        for column in columns:
            data_object[column].append(item[column])

    # 整合结果
    result = {
        'columns': columns,  # 列名数组
        'data': data_object  # 数据对象
    }

    return {"data": result, "dsl": dsl, "query_type": query_type}


@app.route('/api/result-generate', methods=['POST'])
def result_generate():
    dsl = request.json.get('dsl')
    query_type = request.json.get('query_type')
    sql = dsl2sql_impl(dsl, query_type)
    print(sql)
    db_path = os.path.join(os.path.dirname(__file__), '../database/kpi2.db')
    result = sql_client.SqlLiteClient(db_path).execute_sql(sql)
    print(result)
    columns = list(result[0].keys())

    # 初始化数据对象
    data_object = {column: [] for column in columns}

    # 填充数据对象
    for item in result:
        for column in columns:
            data_object[column].append(item[column])

    # 整合结果
    result = {
        'columns': columns,  # 列名数组
        'data': data_object  # 数据对象
    }

    return {"data": result, "dsl": dsl, "query_type": query_type}


@app.route('/api/enums', methods=['GET'])
def get_enums():
    """获取枚举值列表，支持分页和搜索"""
    try:
        page = request.args.get('page', 1, type=int)
        page_size = request.args.get('pageSize', 10, type=int)
        search_word = request.args.get('searchWord', '')
        search_field = request.args.get('searchField', '')
        
        enum_manager = EnumManager()
        result = enum_manager.get_enums(page, page_size, search_word, search_field)
        return jsonify(result)
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@app.route('/api/enums', methods=['POST'])
def add_enum():
    """添加新的枚举值"""
    try:
        data = request.json
        enum_word = data.get('enumWord')
        field = data.get('field')
        
        if not enum_word or not field:
            return jsonify({'success': False, 'message': '枚举值和字段都不能为空'}), 400
            
        enum_manager = EnumManager()
        success = enum_manager.add_enum(enum_word, field)
        return jsonify({'success': success})
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@app.route('/api/enums/<int:enum_id>', methods=['PUT'])
def update_enum(enum_id):
    """更新枚举值"""
    try:
        data = request.json
        enum_word = data.get('enumWord')
        field = data.get('field')
        
        if not enum_word or not field:
            return jsonify({'success': False, 'message': '枚举值和字段都不能为空'}), 400
            
        enum_manager = EnumManager()
        success = enum_manager.update_enum(enum_id, enum_word, field)
        return jsonify({'success': success})
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@app.route('/api/enums/<int:enum_id>', methods=['DELETE'])
def delete_enum(enum_id):
    """删除枚举值"""
    try:
        enum_manager = EnumManager()
        success = enum_manager.delete_enum(enum_id)
        return jsonify({'success': success})
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@app.route('/api/synonyms', methods=['GET'])
def get_synonyms():
    try:
        page = int(request.args.get('page', 1))
        page_size = int(request.args.get('pageSize', 10))
        synonym_search = request.args.get('synonym', '')
        standard_word_search = request.args.get('standardWord', '')
        
        result = SynonymManager().list_synonyms(
            page=page,
            page_size=page_size,
            synonym_search=synonym_search,
            standard_word_search=standard_word_search
        )
        return jsonify(result)
    except Exception as e:
        print(f"获取同义词列表失败: {e}")
        return jsonify({'error': str(e)}), 500


@app.route('/api/synonyms', methods=['POST'])
def add_synonym():
    try:
        data = request.get_json()
        if not data or 'synonym' not in data or 'standardWord' not in data:
            return jsonify({'error': '缺少必要参数'}), 400
        
        success = SynonymManager().add_synonym(
            data['synonym'],
            data['standardWord']
        )
        
        if success:
            return jsonify({'message': '同义词添加成功'})
        else:
            return jsonify({'error': '同义词添加失败'}), 500
    except Exception as e:
        print(f"添加同义词失败: {e}")
        return jsonify({'error': str(e)}), 500


@app.route('/api/synonyms/<int:synonym_id>', methods=['PUT'])
def update_synonym(synonym_id):
    try:
        data = request.get_json()
        if not data or 'synonym' not in data or 'standardWord' not in data:
            return jsonify({'error': '缺少必要参数'}), 400
        
        success = SynonymManager().update_synonym(
            synonym_id,
            data['synonym'],
            data['standardWord']
        )
        
        if success:
            return jsonify({'message': '同义词更新成功'})
        else:
            return jsonify({'error': '同义词更新失败'}), 500
    except Exception as e:
        print(f"更新同义词失败: {e}")
        return jsonify({'error': str(e)}), 500


@app.route('/api/synonyms/<int:synonym_id>', methods=['DELETE'])
def delete_synonym(synonym_id):
    try:
        success = SynonymManager().delete_synonym(synonym_id)
        if success:
            return jsonify({'message': '同义词删除成功'})
        else:
            return jsonify({'error': '同义词删除失败'}), 500
    except Exception as e:
        print(f"删除同义词失败: {e}")
        return jsonify({'error': str(e)}), 500


@app.route('/api/rules', methods=['GET'])
def get_rules():
    """获取规则列表，支持分页和搜索"""
    try:
        page = request.args.get('page', 1, type=int)
        page_size = request.args.get('pageSize', 10, type=int)
        rule_name = request.args.get('ruleName', '')
        rule = request.args.get('rule', '')
        
        result = RuleManager().list_rules(page, page_size, rule_name, rule)
        return jsonify(result)
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@app.route('/api/rules', methods=['POST'])
def add_rule():
    """添加新的规则"""
    try:
        data = request.json
        rule_name = data.get('ruleName')
        rule = data.get('rule')
        
        if not rule_name or not rule:
            return jsonify({'success': False, 'message': '规则名称和规则内容不能为空'}), 400
            
        success = RuleManager().add_rule(rule_name, rule)
        return jsonify({'success': success})
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@app.route('/api/rules/<int:rule_id>', methods=['PUT'])
def update_rule(rule_id):
    """更新规则"""
    try:
        data = request.json
        rule_name = data.get('ruleName')
        rule = data.get('rule')
        
        if not rule_name or not rule:
            return jsonify({'success': False, 'message': '规则名称和规则内容不能为空'}), 400
            
        success = RuleManager().update_rule(rule_id, rule_name, rule)
        return jsonify({'success': success})
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@app.route('/api/rules/<int:rule_id>', methods=['DELETE'])
def delete_rule(rule_id):
    """删除规则"""
    try:
        success = RuleManager().delete_rule(rule_id)
        return jsonify({'success': success})
    except Exception as e:
        return jsonify({'error': str(e)}), 500


if __name__ == '__main__':
    PromptManager().initialize_table()
    QueryModelManager().initialize_table()
    EnumManager().initialize_table()
    SynonymManager().initialize_table()
    RuleManager().initialize_table()
    app.run(host='0.0.0.0', port=5000)



